from django.shortcuts import render,redirect,reverse
from django.contrib.auth import login,logout,authenticate
from django.views.decorators.http import require_POST
from django.http import JsonResponse,HttpResponse
from django.views.generic import View
from .models import User,UserManager
from .forms import LoginForm,SignupForm
from apps.news.models import NewsCategory,WriteNews
from apps.news.forms import WriteNews_Form
from django.db.models import Q
from django.contrib.auth.decorators import permission_required
from django.utils.decorators import method_decorator


class Login_View(View):
	def post(self,request):
		form = LoginForm(request.POST)
		if form.is_valid():
			telephone = form.cleaned_data.get('telephone')
			password = form.cleaned_data.get('password')
			remember = form.cleaned_data.get('remember')

			user = authenticate(username = telephone,password = password)

			if user:
				if user.is_active:
					login(request,user)
					if remember:
						request.session.set_expiry(None)
					else:
						request.session.set_expiry(0)

					return redirect(reverse('index'))

				else:
					return HttpResponse("账号已经被冻结")
			else:
				return HttpResponse('账号或密码错误')
		else:
			return HttpResponse('表单验证失败错误')

	def get(self,request):
		return render(request,'cms/login.html')
	




class Register_View(View):
	def get(self,request):
		return render(request,'cms/register.html')

	def post(self,request):
		form = SignupForm(request.POST)
		if form.is_valid():
			telephone = form.cleaned_data.get('telephone')
			pw1 = form.cleaned_data.get('pw1')
			pw2 = form.cleaned_data.get('pw2')
			username = form.cleaned_data.get('username')
			
			exist = User.objects.filter(telephone = telephone).exists()
			if exist:
				return HttpResponse('这手机号已经被注册，请返回重新注册')
			if pw1 != pw2:
				raise ValueError('两次密码输入不一致')
			if pw1 == pw2:
				try:
					User.objects.create_user(telephone = telephone,username = username,password = pw1)
					return redirect(reverse('index')) 
				except:
					return HttpResponse('用户创建失败') 


		else:
			return HttpResponse('表单验证失败')

def create_user(request):
	user = User.objects.create_superuser(telephone = 19999999999,\
		   username = 'tangtang1',password = 111111)
	return HttpResponse('创建成功')


def logout_view(request):
	logout(request)
	return redirect(reverse('index'))


@permission_required(perm='add_permission',login_url='/')
def cms_index(request):
	return render(request,'cms/cms_index.html')


@permission_required(perm='news.add_writenews',login_url='/')
def write_news(request):
	categories = NewsCategory.objects.all()
	context = {
		'categories': categories
	}
	return render(request,'cms/write_news.html',context = context)


@permission_required(perm='news.add_newscategory',login_url='/')
def news_category(request):
	categories = NewsCategory.objects.all()
	context = {
		'categories': categories
	}
	return render(request,'cms/news_categories.html',context = context)


@method_decorator(permission_required(perm='news.add_newscategory',login_url='/'),name='dispatch')
class Add_Category_View(View):
	def get(self,request):
		return render(request,'cms/add_category.html')

	def post(self,request):
		name = request.POST.get('name')
		exist = NewsCategory.objects.filter(name = name).exists()
		if not exist:
			NewsCategory.objects.create(name = name)
			return redirect(reverse('xfzauth:news_category'))			
		else:
			return HttpResponse('此标签已存在，请返回重新输入')


@method_decorator(permission_required(perm='news.add_newscategory',login_url='/'),name='dispatch')
class Edit_Category_View(View):
	def get(self,request,category_name):
		context = {
			'category_name':category_name	
		}
		return render(request,'cms/edit_category.html',context = context)

	def post(self,request,category_name):
		new_name = request.POST.get('name')
		old_name = NewsCategory.objects.filter(name = category_name)
		old_name.update(name = new_name)
		return redirect(reverse('xfzauth:news_category'))


@permission_required(perm='news.add_newscategory',login_url='/')
def delete_category(request,category_name):
	category_name = NewsCategory.objects.filter(name = category_name)
	category_name.delete()
	return redirect(reverse('xfzauth:news_category'))


@method_decorator(permission_required(perm='news.add_writenews',login_url='/'),name='dispatch')
class Add_News_View(View):
	def get(self,request):
		categories = NewsCategory.objects.all()
		context = {
			'categories': categories
		}
		
		return render(request,'cms/write_news.html',context = context)

	def post(self,request):
		form = WriteNews_Form(request.POST)
		thumbnail = request.FILES.get('thumbnail')
		if form.is_valid():
			title = form.cleaned_data.get('title')
			category_id = form.cleaned_data.get('category')
			desc = form.cleaned_data.get('desc')
			category = NewsCategory.objects.get(pk = category_id)
			content = form.cleaned_data.get('content')
			WriteNews.objects.create(title=title,desc=desc,thumbnail=thumbnail\
				,content = content,author = request.user,category = category)
			return HttpResponse('发布成功')

		else:
			return HttpResponse('发布失败')


@permission_required(perm='news.add_writenews',login_url='/')
def news_list(request):
	if request.method == 'POST':
		title = request.POST.get('title')
		author = request.POST.get('author')
		category = request.POST.get('category')
		if category:
			news = WriteNews.objects.select_related('author','category')\
					.filter(title__icontains=title).filter(author__username__icontains=author)\
					.filter(category=category)
		else:
			news = WriteNews.objects.select_related('author','category')\
					.filter(title__icontains=title).filter(author__username__icontains=author)
	else:
		news = []
	
	categories = NewsCategory.objects.all()
	context = {
		'news':news,
		'categories':categories
	}
	return render(request,'cms/news_list.html',context = context)


@permission_required(perm='news.add_writenews',login_url='/')
def delete_news(request,new_id):
	new = WriteNews.objects.filter(pk = new_id)
	new.delete()
	return render(request,'cms/news_list.html')


@method_decorator(permission_required(perm='add_permission',login_url='/'),name='dispatch')
class Staff_List(View):
	def get(self,request):
		return render(request,'cms/staff_list.html')

	def post(self,request):
		telephone = request.POST.get('telephone')
		username = request.POST.get('username')
		group = request.POST.get('group')
		
		users = User.objects.filter(username__icontains=username).filter(telephone__icontains=telephone)
		if users:
			context = {
				'users':users
			}

			return render(request,'cms/staff_list.html',context = context)

		else:
			return render(request,'cms/staff_list.html')



@permission_required(perm='add_permission',login_url='/')
def delete_staff(request,user_id):
	user = User.objects.get(pk = user_id)
	user.delete()
	return render(request,'cms/staff_list.html')